package cn.jolywood.cloud.module.crm.service.obtainguest;

import cn.hutool.core.collection.CollUtil;
import cn.jolywood.cloud.framework.common.util.collection.MapUtils;
import cn.jolywood.cloud.framework.ip.core.utils.AreaUtils;
import cn.jolywood.cloud.module.crm.dal.redis.no.CrmNoRedisDAO;
import cn.jolywood.cloud.module.system.api.dept.DeptApi;
import cn.jolywood.cloud.module.system.api.user.AdminUserApi;
import cn.jolywood.cloud.module.system.api.user.dto.AdminUserRespDTO;
import com.mzt.logapi.context.LogRecordContext;
import com.mzt.logapi.starter.annotation.LogRecord;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Stream;

import cn.jolywood.cloud.module.crm.controller.admin.obtainguest.vo.*;
import cn.jolywood.cloud.module.crm.dal.dataobject.obtainguest.ObtainGuestDO;
import cn.jolywood.cloud.framework.common.pojo.PageResult;
import cn.jolywood.cloud.framework.common.util.object.BeanUtils;

import cn.jolywood.cloud.module.crm.dal.mysql.obtainguest.ObtainGuestMapper;

import static cn.jolywood.cloud.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.jolywood.cloud.framework.common.util.collection.CollectionUtils.*;
import static cn.jolywood.cloud.module.crm.enums.ErrorCodeConstants.*;
import static cn.jolywood.cloud.module.crm.enums.LogRecordConstants.*;

/**
 * 订单获客主 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class ObtainGuestServiceImpl implements ObtainGuestService {

    @Resource
    private ObtainGuestMapper obtainGuestMapper;

    @Resource
    private CrmNoRedisDAO noRedisDAO;

    @Resource
    private AdminUserApi adminUserApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @LogRecord(type = CRM_OBTAIN_GUEST_TYPE, subType = CRM_OBTAIN_GUEST_CREATE_SUB_TYPE, bizNo = "{{#obtainGuest.id}}",
            success = CRM_OBTAIN_GUEST_CREATE_SUCCESS)
    public Integer createObtainGuest(ObtainGuestSaveReqVO createReqVO,Long userid) {
        // 插入
        ObtainGuestDO obtainGuest = BeanUtils.toBean(createReqVO, ObtainGuestDO.class);

        String no = noRedisDAO.generate(CrmNoRedisDAO.OBTAIN_GUEST_PREFIX);
        if (obtainGuestMapper.selectByNo(no) != null) {
            throw exception(RECEIVABLE_NO_EXISTS);
        }
        obtainGuest.setObtainGuestNo(no);

        obtainGuest.setCreateTime(LocalDateTime.now());
        obtainGuest.setCreator(userid.toString());
        //给与初始值
        obtainGuest.setState(0);

        obtainGuest.setDeleted(false);
        obtainGuestMapper.insert(obtainGuest);

        // 4. 记录操作日志上下文
        LogRecordContext.putVariable("obtainGuest", obtainGuest);

        // 返回
        return obtainGuest.getId();
    }

    @Override
    public void updateObtainGuest(ObtainGuestSaveReqVO updateReqVO) {
        // 校验存在
        validateObtainGuestExists(updateReqVO.getId());
        // 更新
        ObtainGuestDO updateObj = BeanUtils.toBean(updateReqVO, ObtainGuestDO.class);
        obtainGuestMapper.updateById(updateObj);
    }

    @Override
    public void deleteObtainGuest(Integer id) {
        // 校验存在
        validateObtainGuestExists(id);
        // 删除
        obtainGuestMapper.deleteById(id);
    }

    @Override
        public void deleteObtainGuestListByIds(List<Integer> ids) {
        // 删除
        obtainGuestMapper.deleteByIds(ids);
        }


    private void validateObtainGuestExists(Integer id) {
        if (obtainGuestMapper.selectById(id) == null) {

        }
    }

    @Override
    public ObtainGuestRespVO getObtainGuest(Integer id) {
        ObtainGuestDO obtainGuestDO = obtainGuestMapper.selectById(id);
        AdminUserRespDTO user = new AdminUserRespDTO();
        if (obtainGuestDO != null) {
            user = adminUserApi.getUserById(obtainGuestDO.getBusinessManagerId());
        }
        ObtainGuestRespVO bean = BeanUtils.toBean(obtainGuestDO, ObtainGuestRespVO.class);
        //得到客户地址
        bean.setClientAreaName(AreaUtils.format(bean.getClientAreaId()));
        //得到业务经理名称
        bean.setBusinessManagerName(user.getNickname());
        return bean;
    }

    @Override
    public PageResult<ObtainGuestRespVO> getObtainGuestPage(ObtainGuestPageReqVO pageReqVO) {
        PageResult<ObtainGuestDO> pageResult = obtainGuestMapper.selectPage(pageReqVO);
        return new PageResult<>(buildObtainDetailList(pageResult.getList()), pageResult.getTotal());
    }

    private List<ObtainGuestRespVO> buildObtainDetailList(List<ObtainGuestDO> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        // 1 获取业务经理
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(convertListByFlatMap(list,
                contact -> Stream.of(contact.getBusinessManagerId())));
        // 2. 转换成 VO
        return BeanUtils.toBean(list, ObtainGuestRespVO.class, obtainGuestVO -> {
            // 2.1 设置业务经理名称
            MapUtils.findAndThen(userMap, obtainGuestVO.getBusinessManagerId(),
                    user -> obtainGuestVO.setBusinessManagerName(user.getNickname()));
        });
    }

}